import { FormInstance, Modal } from "antd";
import { ForwardRefRenderFunction, RefObject, useImperativeHandle, forwardRef, useRef, useEffect, useState } from "react";
import { CodepenOutlined } from "@ant-design/icons";
import Quill from "quill";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import styled from "styled-components";
import { colorPanel } from "@/asset/data/color";
import { useUploadImage } from "@/hooks";
import { throttle } from "lodash";
import imageResize from "quill-image-resize-module";
import { ImageDrop } from "quill-image-drop-module"; // 拖动加载图片组件。
import { calcSize } from "@/util";
import CodeIcon from "../svg/CodeIcon";
import CodeInput, { CodeInputRef } from "./CodeInput";
import { formatHTML } from "@/api/goods";
import { html } from "@codemirror/lang-html";
Quill.register("modules/imageResize", imageResize);
Quill.register("modules/imageDrop", ImageDrop);

interface RichTextInputProps {
	field?: string;
	formRef?: RefObject<FormInstance>;
	placeholder?: string;
	height?: number;
	onChange?: (value: string) => void;
}
export interface RichTextInputRef {
	setValue: (value: string) => void;
}
const RichTextInput: ForwardRefRenderFunction<RichTextInputRef, RichTextInputProps> = (
	{ field, formRef, placeholder = "", height = 200, onChange },
	ref
) => {
	useImperativeHandle(
		ref,
		() => ({
			setValue: (value: string) => {
				quillInstance.current?.clipboard.dangerouslyPasteHTML(value);
			},
		}),
		[]
	);
	const quillContainer = useRef<HTMLDivElement>(null);
	const { upload } = useUploadImage();
	const quillInstance = useRef<Quill>();
	useEffect(() => {
		if (quillContainer.current) {
			quillInstance.current = new Quill(quillContainer.current, {
				theme: "snow",
				placeholder,
				modules: {
					toolbar: "#toolbar",
					imageResize: {
						//添加
						displayStyles: {
							backgroundColor: "black",
							border: "none",
							color: "white",
						},
						modules: ["Resize", "DisplaySize"],
					},
				},
			});
			quillInstance.current.on("text-change", () => {
				const value = quillInstance.current?.root.innerHTML;
				onChange && onChange(value || '');
				field && formRef?.current?.setFieldValue(field, value);
			});
			quillInstance.current.getModule("toolbar").addHandler(
				"image",
				throttle(() => {
					upload((path) => {
						if (path) {
							const range = quillInstance.current?.getSelection(true);
							if (!range) return;
							quillInstance.current?.insertEmbed(range.index, "image", path);
						}
					});
				})
			);
		}
	}, []);
	const [codeModalOpen, setCodeModalOpen] = useState(false);
	const codeInput = useRef<CodeInputRef>(null);
	return (
		<>
			<StyledToolBar id="toolbar">
				<select className="ql-size" defaultValue="">
					<option value="small">小文本</option>
					<option value="">文本</option>
					<option value="large">二级标题</option>
					<option value="huge">一级标题</option>
				</select>
				<button className="ql-bold"></button>
				<button className="ql-italic"></button>
				<button className="ql-underline"></button>
				<button className="ql-strike"></button>
				<select className="ml-2 ql-color">
					{colorPanel.map((item, index) => (
						<option key={index} value={item} />
					))}
				</select>
				<select className="mr-2 ql-background">
					{colorPanel.map((item, index) => (
						<option key={`bg-${index}`} value={item} />
					))}
				</select>
				<button className="ql-script" value="sub"></button>
				<button className="ql-script" value="super"></button>
				<button style={{ display: "flex" }} className="items-center">
					<CodepenOutlined />
				</button>
				<button className="ql-link"></button>
				<button className="ql-image"></button>
				<button
					onClick={async () => {
						setCodeModalOpen(true);
						const html = quillInstance.current?.root.innerHTML;
						if (html) {
							let result = html;
							try {
								const res = await formatHTML({ code: html });
								result = res.data || "";
							} finally {
								codeInput.current?.setValue(result);
							}
						}
					}}
				>
					<CodeIcon />
				</button>
			</StyledToolBar>
			<div style={{ height: calcSize(height) }} ref={quillContainer}></div>
			<Modal
				width={900}
				open={codeModalOpen}
				title="编辑HTML"
				onCancel={() => setCodeModalOpen(false)}
				onOk={() => {
					const value = codeInput.current?.getValue();
					value && quillInstance.current?.clipboard.dangerouslyPasteHTML(value);
					setCodeModalOpen(false);
				}}
			>
				<CodeInput extensions={[html()]} height="600px" ref={codeInput} />
			</Modal>
		</>
	);
};

export default forwardRef(RichTextInput);
export const StyledToolBar = styled.div`
	.ql-color,
	.ql-background {
		.ql-picker-options {
			width: 212px !important;
		}
	}
	button {
		&:hover {
			svg {
				fill: #06c;
			}
		}
	}
`;
